package HTTP

import (
	"SQL/FSDB"
	"fmt"
	"net/http"
)

func confirmAddGroupMember(w http.ResponseWriter, req *http.Request) {

	var resCode = http.StatusOK
	var msg = ""
	var res interface{}
	defer func() {
		writeResult(w, resCode, msg, res)
	}()

	groupID := req.FormValue("groupID")

	ok := false
	if ok, resCode, msg = isValidID(groupID, "GroupID"); !ok {
		if resCode == errInvalidID {
			msg = mInvalidGroupID
		}
		return
	}

	req.ParseForm()
	maxLen := 20
	count := 0
	memberIDs := make([]string, 0)

	for _, memberID := range req.Form["memberID"] {

		if ok, resCode, msg = isValidID(memberID, "MemberID"); !ok {
			msg = mInvalidMemberID
			return
		}
		memberIDs = append(memberIDs, memberID)
		count++
		if count >= maxLen {
			msg = "每次添加成员的数量为 0~20 ！"
			resCode = errInvalidArgLength
			return
		}
	}

	errCode, errMsg := addGroupMemberToDB(groupID, memberIDs)
	msg = errMsg
	if errCode != Success {
		resCode = errCode
		return
	}
}

func addGroupMemberToDB(groupID string, memberIDs []string) (errCode int, errMsg string) {

	addMemberSQL := `INSERT INTO members(groupid,userid) VALUES`
	count := len(memberIDs) - 1
	for index, memberID := range memberIDs {
		value := fmt.Sprintf("(%s,%s)", groupID, memberID)
		addMemberSQL += value
		if index != count {
			addMemberSQL += ","
		}
	}
	_, err := FSDB.Exec(addMemberSQL)
	if err != nil {
		return errDBExecFailed, err.Error()
	}
	return Success, "增加群成员成功！"
}
